#light

open Langexplr.Abc
open Langexplr.Abc.InstructionUtilities
open Langexplr.Abc.AvmActivePatterns
open System.IO


let abcFile = using (new FileStream("test.abc",FileMode.Open)) ( 
                    fun stream -> AvmAbcFile.Create(stream))


let printInstructions = 
   [Pop;
    FindPropertyStrict(CQualifiedName(Ns("",NamespaceKind.Namespace),
                                                                   "print"));
    PushString "Hola!";
    CallProperty(CQualifiedName(Ns("",NamespaceKind.Namespace),"print"),1);Pop]


let modifyCode(b:AvmMethodBody option) = 
  match b with
  | Some(AvmMethodBody(lc,ms,isd,msd,instructions,ex,traits)) ->      
       AvmMethodBody(lc,
                     ms,
                     isd,
                     msd,
                     (List.foldBack
                            (fun i r -> 
                                match i with
                                | Pop -> 
                                      (List.append 
                                         printInstructions   r) 
                                | _ -> (i::r)) 
                            (Array.toList instructions) [])
                     |> List.toArray,
                     ex,traits) |> Some

let modifyFile(f:AvmAbcFile) =
  match f with
  | AvmAbcFile(
               [AvmScript(
                          AvmMethod(name,
                                    returnType,
                                    parameters,
                                    body),smembers)],
               classes) -> 
               AvmAbcFile(
                          [AvmScript(
                                     AvmMethod(name,
                                               returnType,
                                               parameters,
                                               modifyCode(body)),smembers)],
                          classes)

let modifiedAbcFile = modifyFile(abcFile)

printf "loaded!"

let abcFileCreator = AbcFileCreator()
let file = modifiedAbcFile.ToLowerIr(abcFileCreator)

let foo(f) =
   printf "%s" (f.ToString()) 
foo(file)

using (new BinaryWriter(new FileStream("test_t.abc",FileMode.Create))) 
      (fun f -> file.WriteTo(f))


let abcFile2 = using (new FileStream("test_t.abc",FileMode.Open)) ( 
                    fun stream -> AvmAbcFile.Create(stream))

printf "loaded2!"
